﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Aliyeye.Car.Net.UI.SystemHelp;
using Aliyeye.Car.Net.UI.Common;
using Aliyeye.Car.Net.UI.PopupDialog;
using Aliyeye.Car.Net.UI.CarModel;
using Aliyeye.Car.Net.UI.PrintExport;
using Aliyeye.Car.Net.UI.SystemAdmin;

namespace Aliyeye.Car.Net.UI.OrderModel
{
    public partial class ReserveShortWithDriver : Aliyeye.Car.Net.UI.BaseForm
    {
        CarSvc.SoapHeaderClass sopaHeaderCAR = new Aliyeye.Car.Net.UI.CarSvc.SoapHeaderClass();
        ReserveSvc.SoapHeaderClass sopaHeaderReserveSvc = new Aliyeye.Car.Net.UI.ReserveSvc.SoapHeaderClass();
        private int carId = 0;
        private int reserveID = 0;
        int intHours = 0;
        CarSvc.Car modelCar = new Aliyeye.Car.Net.UI.CarSvc.Car();
        ReserveSvc.Reserve modelReserve = new Aliyeye.Car.Net.UI.ReserveSvc.Reserve();
        Model.Customer customerInfo = new Model.Customer();

        int customID = 0;
        string customerName = "";
        string customerCode = "";

        public ReserveShortWithDriver()
        {
            InitializeComponent();
            txtCode.Text = Login.GetOrderNumber();
            dtBookDate.MinDate = DateTime.Now;

            //客户登陆，违章保留固定
            if (Login.CustomID != 0)
            {
                txtZPrice2.Enabled = false;
            }
        }

        public ReserveShortWithDriver(int id)
        {
            InitializeComponent();
            carId = id;
            txtCode.Text = Login.GetOrderNumber();
            //客户登陆，违章保留固定
            if (Login.CustomID != 0)
            {
                txtZPrice2.Enabled = false;
            }
        }

        public ReserveShortWithDriver(int resID, int id)
        {
            InitializeComponent();
            reserveID = resID;
            carId = id;
            txtCode.Text = Login.GetOrderNumber();
            //客户登陆，违章保留固定
            if (Login.CustomID != 0)
            {
                txtZPrice2.Enabled = false;
            }
        }

        string AirportShuttleOneWay = string.Empty;
        string AirportShuttleTwoWay = string.Empty;
        string Chartered3Rent = string.Empty;
        string Chartered8Rent = string.Empty;
        string OutdatedFee3 = string.Empty;
        string OutdatedFee8 = string.Empty;
        string LongJourneys1 = string.Empty;
        string LongJourneys2 = string.Empty;
        string LongJourneys3 = string.Empty;


        public ReserveShortWithDriver(int resID, int id, string AirportShuttleOneWay, string AirportShuttleTwoWay,
            string Chartered3Rent, string Chartered8Rent, string OutdatedFee3, string OutdatedFee8,
            string LongJourneys1, string LongJourneys2, string LongJourneys3)
        {
            InitializeComponent();
            reserveID = resID;
            carId = id;
            txtCode.Text = Login.GetOrderNumber();

            this.AirportShuttleOneWay = AirportShuttleOneWay;
            this.AirportShuttleTwoWay = AirportShuttleTwoWay;
            this.Chartered3Rent = Chartered3Rent;
            this.Chartered8Rent = Chartered8Rent;
            this.OutdatedFee3 = OutdatedFee3;
            this.OutdatedFee8 = OutdatedFee8;
            this.LongJourneys1 = LongJourneys1;
            this.LongJourneys2 = LongJourneys2;
            this.LongJourneys3 = LongJourneys3;
            //客户登陆，违章保留固定
            if (Login.CustomID != 0)
            {
                txtZPrice2.Enabled = false;
            }
        }

        private bool isGetCar = false;
        public ReserveShortWithDriver(int resID, int id, string AirportShuttleOneWay, string AirportShuttleTwoWay,
           string Chartered3Rent, string Chartered8Rent, string OutdatedFee3, string OutdatedFee8,
           string LongJourneys1, string LongJourneys2, string LongJourneys3, bool getCar)
        {
            InitializeComponent();
            reserveID = resID;
            carId = id;
            txtCode.Text = Login.GetOrderNumber();

            this.AirportShuttleOneWay = AirportShuttleOneWay;
            this.AirportShuttleTwoWay = AirportShuttleTwoWay;
            this.Chartered3Rent = Chartered3Rent;
            this.Chartered8Rent = Chartered8Rent;
            this.OutdatedFee3 = OutdatedFee3;
            this.OutdatedFee8 = OutdatedFee8;
            this.LongJourneys1 = LongJourneys1;
            this.LongJourneys2 = LongJourneys2;
            this.LongJourneys3 = LongJourneys3;

            isGetCar = getCar;
            //客户登陆，违章保留固定
            if (Login.CustomID != 0)
            {
                txtZPrice2.Enabled = false;
            }
        }

        private void BindInfo()
        {
            overlay.FadeIn(); Cursor.Current = Cursors.WaitCursor;
            ServiceManipulator.SafeAsyncExecution<CarSvc.CarServiceSoapClient>(
                proxy => proxy.GetModel(sopaHeaderCAR, carId),
                result =>
                {
                    if (result.Error == null)
                    {
                        modelCar = (CarSvc.Car)result.Result;
                        if (modelCar != null)
                        {
                            lblBrand.Text = modelCar.Brand.ToString();
                            lblCartype.Text = modelCar.Cartype.ToString();
                            lblcode.Text = modelCar.Code.ToString();
                            lblDayKm.Text = modelCar.DayLimitKM.ToString();
                            lblOvertimePrie.Text = modelCar.OvertimePrie.ToString();
                            lblowner.Text = modelCar.DriverName.ToString();
                            lblTimeoutPrie.Text = modelCar.TimeoutPrie.ToString();
                            lblUser.Text = Login.LogUserName.ToString();
                            txtZPrice.Enabled = false;
                            //txtZPrice.Text = modelCar.DayRent.ToString();
                            //txtZPrice2.Text = modelCar.DayRent.ToString();
                            txtMax.Text = modelCar.Max.ToString();
                        }
                        overlay.FadeOut(); Cursor.Current = Cursors.Default;
                    }
                    else
                    {
                        PageCommon.Error(result.Error.Message); overlay.FadeOut(); Cursor.Current = Cursors.Default;
                    }
                },
                this
            );

            if (reserveID > 0)
            {
                ServiceManipulator.SafeAsyncExecution<ReserveSvc.ReserveServiceSoapClient>(
                    proxy => proxy.GetModel(sopaHeaderReserveSvc, reserveID),
                    result =>
                    {
                        if (result.Error == null)
                        {
                            modelReserve = (ReserveSvc.Reserve)result.Result;
                            txtAriAddr.Text = modelReserve.AriAddr;
                            txtAriAddr2.Text = modelReserve.SenAddr;
                            txtCode.Text = modelReserve.Code;
                            txtFlayCode.Text = modelReserve.FlayCode;
                            txtLivAddr.Text = modelReserve.LivAddr;
                            txtMarks.Text = modelReserve.Marks;
                            txtcustcode.Text = customerCode = customerInfo.Code = modelReserve.CustomerCode;
                            txtName.Text = customerName = customerInfo.Name = modelReserve.CustomerName;
                            txtRent.Text = modelReserve.Rent.ToString();
                            txtZPrice.Text = modelReserve.ZPrice.ToString();
                            txtZPrice2.Text = modelReserve.ZPrice.ToString();
                            lblDeadLine.Text = modelReserve.DeadLine.ToString() + " 天";
                            cmbpaytype.Text = modelReserve.PayType;
                            dtBookDate.Value = modelReserve.BookTime;
                            dtEndDate.Value = modelReserve.EndBooktime;
                            customID = modelReserve.CustId;
                            customerName = modelReserve.CustomerName;

                            lblUser.Text = modelReserve.UserTrueName;
                            customerInfo.Tel = modelReserve.Tel;
                            customerInfo.ComName = modelReserve.ComName;

                            cmb001.Text = modelReserve.PriceType1;
                            cmb002.Text = modelReserve.PriceType2;
                            txtOutdatedFee.Text = modelReserve.OutdatedFee.ToString();

                            txtMax.Text = modelReserve.CurrentMax.ToString();
                            if (modelReserve.IsGetCar)
                                rdbGetCar.Checked = true;
                            else
                                rdbNoGetCar.Checked = true;

                            //取车
                            if (isGetCar)
                            {
                                rdbGetCar.Checked = true;
                                rdbNoGetCar.Checked = false;
                            }

                            //不显示积分信息
                            unDisplayPoints();
                            //overlay.FadeOut();Cursor.Current = Cursors.Default;
                        }
                        else
                        {
                            PageCommon.Error(result.Error.Message); overlay.FadeOut(); Cursor.Current = Cursors.Default;
                        }
                    },
                    this
                );

                foreach (Control cont in this.groupBox1.Controls)
                {
                    cont.Enabled = false;
                }
                foreach (Control cont in this.groupBox2.Controls)
                {
                    cont.Enabled = false;
                }

                btnCancel.Enabled = true;
                btnPrint.Enabled = true;

                //取车
                if (isGetCar)
                {
                    txtMax.Enabled = true;
                    btnPrint.Enabled = false;
                    btnSave.Enabled = true;
                    rdbGetCar.Checked = true;
                    rdbNoGetCar.Checked = false;
                    txtRent.Enabled = true;
                    cmbpaytype.Enabled = true;
                    txtZPrice2.Enabled = true;
                }
            }
        }

        private void BindComboBoxInfo()
        {
            overlay.FadeIn(); Cursor.Current = Cursors.WaitCursor;
            ArchivesSvc.SoapHeaderClass sopaHeaderRole = new Aliyeye.Car.Net.UI.ArchivesSvc.SoapHeaderClass();

            ServiceManipulator.SafeAsyncExecution<ArchivesSvc.ArchivesServiceSoapClient>(
                proxy => proxy.ComBoxPay(sopaHeaderRole),
                result =>
                {
                    if (result.Error == null)
                    {
                        DataSet dtRole = (DataSet)result.Result;
                        cmbpaytype.DisplayMember = "Namevalue";
                        cmbpaytype.ValueMember = "Id";
                        cmbpaytype.DataSource = dtRole.Tables[0];
                        cmbpaytype.SelectedIndex = 0;
                        overlay.FadeOut(); Cursor.Current = Cursors.Default;
                    }
                    else
                    {
                        PageCommon.Error(result.Error.Message); overlay.FadeOut(); Cursor.Current = Cursors.Default;
                    }
                },
                this
            );

            cmb001.SelectedIndex = 0;
            cmb002.SelectedIndex = 0;
        }

        private void txtRent_KeyPress(object sender, KeyPressEventArgs e)
        {
            IsNumberMoney(txtRent, e);
        }

        private bool IsNumberMoney(System.Windows.Forms.TextBox t, KeyPressEventArgs e)
        {
            if ((e.KeyChar >= '0' && e.KeyChar <= '9' || e.KeyChar == '.' || e.KeyChar == 8 || e.KeyChar == 13))
            {
                //lb.Text=string.Empty;
                return true;
            }
            else
            {
                DialogNotify diaSecc = new DialogNotify("只能输入数字！");
                diaSecc.ShowDialog();
                e.Handled = true;
                return false;
            }
        }

        private void menuBlueButton2_Click(object sender, EventArgs e)
        {

            // overlay.FadeIn();Cursor.Current = Cursors.WaitCursor;

        }

        private void ReserveShortWithDriver_Load(object sender, EventArgs e)
        {
            if (Login.CustomID != 0)
            {
                btnAddCustomer.Visible = false;
                txtcustcode.Enabled = false;
                txtcustcode.Text = Login.CustomerCode;
                txtName.Text = Login.CustomerName;
                txtName.Enabled = false;
                customID = Login.CustomID;
            }

            BindComboBoxInfo();
            dgvInfo.AutoGenerateColumns = false;
            if (carId > 0)
            {
                BindInfo();
                if (reserveID == 0)
                {
                    BindDateInfo();
                }
                else
                {
                    dgvUseDate.Visible = false;
                    lkbSelectOtherDate.Visible = false;
                    lblDateTitle.Visible = false;
                    lkbSelectOtherDate.Enabled = false;
                }
            }
        }

        //保存
        private void btnSave_Click(object sender, EventArgs e)
        {
            //取车
            if (isGetCar)
            {
                GetCar();
                return;
            }
            SaveInfo();
        }

        private void GetCar()
        {
            Int64 max = 0;
            if (!string.IsNullOrEmpty(this.txtMax.Text))
            {
                try
                {

                    max = Convert.ToInt32(this.txtMax.Text);
                    if (max < 0)
                    {
                        DialogWarning dia = new DialogWarning("当前公里数不能为负数！");
                        dia.ShowDialog();
                        return;
                    }
                }
                catch
                {
                    DialogWarning dia = new DialogWarning("当前公里数应该为整数！");
                    dia.ShowDialog();
                    return;
                }
            }

            if (string.IsNullOrEmpty(txtRent.Text))
            {
                PageCommon.Alert("预收租金不能为空！");
                return;
            }

            if (!string.IsNullOrEmpty(this.txtRent.Text))
            {
                try
                {

                    Decimal txtRent2 = Convert.ToDecimal(this.txtRent.Text);
                    if (txtRent2 < 0)
                    {
                        DialogWarning dia = new DialogWarning("预收租金不能为负数！");
                        dia.ShowDialog();
                        return;

                    }
                }
                catch
                {
                    DialogWarning dia = new DialogWarning("请填入正确的预收租金数！");
                    dia.ShowDialog();
                    return;
                }
            }

            decimal decimalZPrice = 0;
            if (!string.IsNullOrEmpty(this.txtZPrice2.Text))
            {
                try
                {

                    decimalZPrice = Convert.ToDecimal(this.txtZPrice2.Text);
                    if (decimalZPrice < 0)
                    {
                        DialogWarning dia = new DialogWarning("优惠价不能为负数！");
                        dia.ShowDialog();
                        return;

                    }
                }
                catch
                {
                    DialogWarning dia = new DialogWarning("请输入正确的优惠价！");
                    dia.ShowDialog();
                    return;
                }
            }

            if (cmbpaytype.Text.Trim() == "会员积分")
            {
                decimal zPrice = Convert.ToDecimal(this.txtZPrice2.Text);

                if (zPrice > customerInfo.Points)
                {
                    PageCommon.Alert("会员当前可用积分不足，请选择其它付款方式！");
                    return;
                }
                else
                {
                    modelReserve.Points = Convert.ToInt64(Math.Round(zPrice, 0));
                }
            }

            if (string.IsNullOrEmpty(txtZPrice2.Text))
            {
                PageCommon.Alert("优惠价不能为空！");
                return;
            }


            decimal decimalRent = Convert.ToDecimal(this.txtRent.Text);
            string strPayType = this.cmbpaytype.Text;

            overlay.FadeIn(); Cursor.Current = Cursors.WaitCursor;
            ReserveSvc.SoapHeaderClass sopaHeaderReserveSvc = new Aliyeye.Car.Net.UI.ReserveSvc.SoapHeaderClass();

            ServiceManipulator.SafeAsyncExecution<ReserveSvc.ReserveServiceSoapClient>(
                proxy => proxy.GetCar(sopaHeaderReserveSvc, reserveID, carId, Convert.ToInt64(txtMax.Text), decimalRent, strPayType, decimalZPrice),
                result =>
                {
                    if (result.Error == null)
                    {
                        PageCommon.Notify("取车成功！");
                        modelReserve.CurrentMax = Convert.ToInt64(txtMax.Text);
                        overlay.FadeOut(); Cursor.Current = Cursors.Default;
                        txtMax.Enabled = false;
                        btnPrint.Enabled = true;
                        btnSave.Enabled = false;
                        txtRent.Enabled = false;
                        cmbpaytype.Enabled = false;
                        txtZPrice2.Enabled = false;
                        modelReserve.ZPrice = decimalZPrice;
                        modelReserve.Rent = decimalRent;
                        modelReserve.PayType = strPayType;
                        modelCar.Max = Convert.ToInt64(txtMax.Text);
                    }
                    else
                    {
                        PageCommon.Error(result.Error.Message); overlay.FadeOut(); Cursor.Current = Cursors.Default;
                    }
                },
                this
            );
        }


        private void SaveInfo()
        {
            if (!VerifyInfo())
                return;

            if (cmbpaytype.Text.Trim() == "会员积分")
            {
                decimal zPrice = Convert.ToDecimal(this.txtZPrice2.Text);


                if (zPrice > customerInfo.Points)
                {
                    PageCommon.Alert("会员当前可用积分不足，请选择其它付款方式！");
                    return;
                }
                else
                {
                    modelReserve.Points = Convert.ToInt64(Math.Round(zPrice, 0));
                }
            }

            //ReserveSvc.Reserve model = new Aliyeye.Car.Net.UI.ReserveSvc.Reserve();
            modelReserve.Rent = Convert.ToDecimal(txtRent.Text);
            modelReserve.ZPrice = Convert.ToDecimal(txtZPrice2.Text);
            modelReserve.DeadLine = intHours;
            modelReserve.DeadLineType = "次";
            modelReserve.DeadLine = 1;
            modelReserve.PriceType1 = cmb001.Text;
            modelReserve.PriceType2 = cmb002.Text;
            if (cmb002.Text.Trim() == "包车三小时租金" || cmb002.Text.Trim() == "包车八小时租金")
                modelReserve.OutdatedFee = Convert.ToDecimal(txtOutdatedFee.Text);
            else
                modelReserve.OutdatedFee = 0;

            modelReserve.FlayCode = txtFlayCode.Text;
            modelReserve.PayType = cmbpaytype.Text;
            modelReserve.LivAddr = txtLivAddr.Text;
            modelReserve.AriAddr = txtAriAddr.Text;
            modelReserve.SenAddr = txtAriAddr2.Text;
            DateTime dtBeginDate = dtBookDate.Value;
            DateTime dtEDate = dtEndDate.Value;
            modelReserve.BookTime = new DateTime(dtBeginDate.Year, dtBeginDate.Month, dtBeginDate.Day, dtBeginDate.Hour, dtBeginDate.Minute, 0);
            modelReserve.EndBooktime = new DateTime(dtEDate.Year, dtEDate.Month, dtEDate.Day, dtEDate.Hour, dtEDate.Minute, 0);

            modelReserve.Code = txtCode.Text;
            modelReserve.CustId = customID;
            modelReserve.ysTime = "";
            modelReserve.Endystime = "";
            modelReserve.Marks = txtMarks.Text;
            modelReserve.CarId = carId;

            modelReserve.UserId = Login.LogUserId;
            modelReserve.Type = 4;//短租带驾
            modelReserve.InpuTime = DateTime.Now;

            modelReserve.OrderSataus = false;

            modelReserve.PriceType1 = cmb001.Text;
            modelReserve.PriceType2 = cmb002.Text;
            if (!string.IsNullOrEmpty(txtOutdatedFee.Text))
                modelReserve.OutdatedFee = Convert.ToDecimal(txtOutdatedFee.Text);
            else
                modelReserve.OutdatedFee = 0;
            modelReserve.DeadLineType = "次";
            modelReserve.CurrentMax = Convert.ToInt64(txtMax.Text);
            modelReserve.IsGetCar = rdbGetCar.Checked;

            if (reserveID == 0)
            {
                //添加
                ServiceManipulator.SafeAsyncExecution<ReserveSvc.ReserveServiceSoapClient>(
                    proxy => proxy.Add(sopaHeaderReserveSvc, modelReserve),
                    result =>
                    {
                        if (result.Error == null)
                        {
                            //overlay.FadeOut();Cursor.Current = Cursors.Default;
                            reserveID = modelReserve.Id = Convert.ToInt32(result.Result);
                            isSave = true;
                        }
                        else
                        {
                            PageCommon.Error(result.Error.Message); overlay.FadeOut(); Cursor.Current = Cursors.Default;
                        }
                    },
                    this
                );
            }
            else
            {
                //修改
                //model.Id = reserveID;
                ServiceManipulator.SafeAsyncExecution<ReserveSvc.ReserveServiceSoapClient>(
                proxy => proxy.Update(sopaHeaderReserveSvc, modelReserve),
                result =>
                {
                    if (result.Error == null)
                    {
                        //PageCommon.Notify("修改订车信息成功！");
                        //overlay.FadeOut();Cursor.Current = Cursors.Default;
                        //this.Close();
                    }
                    else
                    {
                        PageCommon.Error(result.Error.Message); overlay.FadeOut(); Cursor.Current = Cursors.Default;
                    }
                },
                this
            );
            }

            //更新车辆状态
            ServiceManipulator.SafeAsyncExecution<CarSvc.CarServiceSoapClient>(
            proxy => proxy.UpdateCarStatus(sopaHeaderCAR, carId, modelReserve.EndBooktime, true),
            result =>
            {
                if (result.Error == null)
                {
                    PageCommon.Notify("保存订车信息成功！");
                    overlay.FadeOut(); Cursor.Current = Cursors.Default;

                    foreach (Control con in this.groupBox1.Controls)
                    {
                        if (con is TextBox)
                            con.Enabled = false;
                    }

                    foreach (Control con in this.groupBox2.Controls)
                    {
                        if (con is TextBox)
                            con.Enabled = false;

                        if (con is DateTimePicker)
                            con.Enabled = false;

                        if (con is ComboBox)
                            con.Enabled = false;

                        if (con is RadioButton)
                            con.Enabled = false;
                    }
                    btnSave.Enabled = false;
                    lkbSelectOtherDate.Enabled = false;
                }
                else
                {
                    PageCommon.Error(result.Error.Message); overlay.FadeOut(); Cursor.Current = Cursors.Default;
                }
            },
            this
        );

        }

        //验证
        private bool VerifyInfo()
        {
            bool result = true;
            if (string.IsNullOrEmpty(this.txtCode.Text))
            {
                DialogWarning dia = new DialogWarning("内部编号号不能为空！");
                dia.ShowDialog();
                result = false; return result;
            }
            if (customID == 0)
            {
                DialogWarning dia = new DialogWarning("请选择客户！");
                dia.ShowDialog();
                result = false; return result;
            }

            if (string.IsNullOrEmpty(txtcustcode.Text))
            {
                DialogWarning dia = new DialogWarning("客户编号不能为空！");
                dia.ShowDialog();
                result = false; return result;
            }

            if (string.IsNullOrEmpty(txtName.Text))
            {
                DialogWarning dia = new DialogWarning("客户名不能为空！");
                dia.ShowDialog();
                result = false; return result;
            }

            if (string.IsNullOrEmpty(txtRent.Text))
            {
                PageCommon.Alert("预收租金不能为空！");
                result = false; return result;
            }

            if (string.IsNullOrEmpty(txtZPrice.Text))
            {
                PageCommon.Alert("租赁单价不能为空！");
                result = false; return result;
            }

            if (string.IsNullOrEmpty(txtZPrice2.Text))
            {
                PageCommon.Alert("优惠价不能为空！");
                result = false; return result;
            }

            if (string.IsNullOrEmpty(txtLivAddr.Text))
            {
                PageCommon.Alert("出发地点不能为空！");
                result = false; return result;
            }

            if (string.IsNullOrEmpty(txtAriAddr.Text))
            {
                PageCommon.Alert("前往地点不能为空！");
                result = false; return result;
            }

            Int64 max = 0;
            if (!string.IsNullOrEmpty(this.txtMax.Text))
            {
                try
                {

                    max = Convert.ToInt32(this.txtMax.Text);
                    if (max < 0)
                    {
                        DialogWarning dia = new DialogWarning("当前公里数不能为负数！");
                        dia.ShowDialog();
                        result = false; return result;

                    }
                }
                catch
                {
                    DialogWarning dia = new DialogWarning("当前公里数应该为整数！");
                    dia.ShowDialog();
                    result = false; return result;
                }
            }

            decimal price2 = 0;
            if (!string.IsNullOrEmpty(this.txtZPrice2.Text))
            {
                try
                {

                    price2 = Convert.ToDecimal(this.txtZPrice2.Text);
                    if (price2 < 0)
                    {
                        DialogWarning dia = new DialogWarning("优惠价不能为负数！");
                        dia.ShowDialog();
                        result = false; return result;

                    }
                }
                catch
                {
                    DialogWarning dia = new DialogWarning("请输入正确的优惠价！");
                    dia.ShowDialog();
                    result = false; return result;
                }
            }

            return result;
        }

        private void txtName_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                string strSearch = txtName.Text;
                if (string.IsNullOrEmpty(strSearch))
                {
                    DialogWarning dia = new DialogWarning("客户名不能为空！");
                    dia.ShowDialog();
                    return;
                }
                else
                {
                    DisplayCustomeLIst(strSearch, "姓名");
                }
            }
        }

        private void txtcustcode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                string strSearch = txtcustcode.Text;
                if (string.IsNullOrEmpty(strSearch))
                {
                    DialogWarning dia = new DialogWarning("客户编号不能为空！");
                    dia.ShowDialog();
                    return;
                }
                else
                {
                    DisplayCustomeLIst(strSearch, "客户编号");
                }
            }
        }

        private void DisplayCustomeLIst(string strSearch, string type)
        {
            if (string.IsNullOrEmpty(strSearch))
            {
                return;
            }

            overlay.FadeIn(); Cursor.Current = Cursors.WaitCursor;
            string strSelectWhere = "";
            if (type == "姓名")
            {
                strSelectWhere = " Name like '%" + strSearch + "%'";
            }
            if (type == "客户编号")
            {
                strSelectWhere = " Code like '%" + strSearch + "%'";
            }
            DataSet ds = null;
            dgvInfo.DataSource = null;
            dgvInfo.AutoGenerateColumns = false;
            CustomerSvc.SoapHeaderClass sopaHeader = new Aliyeye.Car.Net.UI.CustomerSvc.SoapHeaderClass();
            ServiceManipulator.SafeAsyncExecution<CustomerSvc.CustomerServiceSoapClient>(
                proxy => proxy.GetList(sopaHeader, strSelectWhere),
                result =>
                {
                    if (result.Error == null)
                    {
                        ds = (DataSet)result.Result;
                        if (ds != null && ds.Tables[0].Rows.Count > 0)
                        {
                            dgvInfo.DataSource = ds.Tables[0];
                            this.dgvInfo.Visible = true;
                            this.dgvInfo.Focus();
                        }
                        else
                        {
                            txtcustcode.Text = customerCode;
                            txtName.Text = customerName;
                            PageCommon.Alert("查找的客户不存在，请重新查找！");
                        }
                        overlay.FadeOut(); Cursor.Current = Cursors.Default;
                    }
                    else
                    {
                        PageCommon.Error(result.Error.Message); overlay.FadeOut(); Cursor.Current = Cursors.Default;
                    }
                },
                this
            );

        }

        private void dgvInfo_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            if (this.dgvInfo.Rows.Count != 0)
            {
                for (int i = 0; i < this.dgvInfo.Rows.Count; )
                {
                    this.dgvInfo.Rows[i].DefaultCellStyle.BackColor = System.Drawing.Color.PapayaWhip;
                    i += 2;
                }
            }
        }

        private void dgvInfo_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Return)
            {
                customerInfo.Id = Convert.ToInt32(this.dgvInfo.CurrentRow.Cells["编号"].Value.ToString());
                customerInfo.Name = this.dgvInfo.CurrentRow.Cells[1].Value.ToString();
                customerInfo.Tel = this.dgvInfo.CurrentRow.Cells["移动电话"].Value.ToString();
                customerInfo.ComName = this.dgvInfo.CurrentRow.Cells["单位名称"].Value.ToString();
                customerInfo.CodeCar = this.dgvInfo.CurrentRow.Cells["身份证号"].Value.ToString();
                customerInfo.Phone = this.dgvInfo.CurrentRow.Cells["电话"].Value.ToString();
                customerInfo.DriCard = this.dgvInfo.CurrentRow.Cells["驾驶证号"].Value.ToString();
                customerInfo.Addr = this.dgvInfo.CurrentRow.Cells["住址"].Value.ToString();
                customerInfo.Points = Convert.ToInt64(this.dgvInfo.CurrentRow.Cells["Points"].Value.ToString());

                this.txtcustcode.Text = this.dgvInfo.CurrentRow.Cells[0].Value.ToString();
                this.txtName.Text = this.dgvInfo.CurrentRow.Cells[1].Value.ToString();
                customID = Convert.ToInt32(this.dgvInfo.CurrentRow.Cells["编号"].Value.ToString());
                customerName = this.txtName.Text;
                customerCode = this.txtcustcode.Text;
                this.dgvInfo.Visible = false;
                this.txtRent.Focus();

                if (cmbpaytype.Text.Trim() == "会员积分")
                {
                    displayPoints();
                }
                else
                {
                    unDisplayPoints();
                }
            }
        }

        //取消
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        bool isSave = false;
        //返回
        private void btnReturn_Click(object sender, EventArgs e)
        {
            //if (PageCommon.Confirm("所做的信息操作保存吗？"))
            //{
            //    SaveInfo();
            //}
            //else
            //{
            //    this.Close();
            //}

            if (!isSave)
            {
                if (PageCommon.Confirm("你还未存盘，现在存盘吗？"))
                {
                    SaveInfo();
                }
                else
                {
                    this.Close();
                }
            }
            else
            {
                this.Close();
            }
        }

        //打印派车单
        private void btnPrint_Click(object sender, EventArgs e)
        {
            if (reserveID == 0)
            {
                PageCommon.Alert("请先存盘后再打印！");
                return;
            }

            //BindInfo();

            DataSet ds = null;
            CompanySvc.SoapHeaderClass sopaHeaderCompany = new CompanySvc.SoapHeaderClass();
            overlay.FadeIn(); Cursor.Current = Cursors.WaitCursor;
            ServiceManipulator.SafeAsyncExecution<CompanySvc.CompanyServiceSoapClient>(
                    proxy => proxy.GetList(sopaHeaderCompany, ""),
                    result =>
                    {
                        string msg = "OK";
                        if (result.Error == null)
                        {
                            ds = (DataSet)result.Result;
                            if (ds.Tables[0].Rows.Count > 0)
                            {
                                Model.Company model = new Model.Company();

                                model.ComName = ds.Tables[0].Rows[0]["ComName"].ToString();
                                model.ComAddr = ds.Tables[0].Rows[0]["ComAddr"].ToString();
                                model.Tel = ds.Tables[0].Rows[0]["Tel"].ToString();
                                model.Fax = ds.Tables[0].Rows[0]["Fax"].ToString();
                                model.EMail = ds.Tables[0].Rows[0]["EMail"].ToString();
                                model.UserName = ds.Tables[0].Rows[0]["UserName"].ToString();
                                model.Url = ds.Tables[0].Rows[0]["Url"].ToString();
                                model.Marks = ds.Tables[0].Rows[0]["Marks"].ToString();

                                //开始打印派车单
                                WordHelper wordHelp = new WordHelper();
                                if (wordHelp.ShortWithDriverPrint(model, customerInfo, modelReserve, modelCar, out msg))
                                {
                                    PageCommon.Notify("打印成功！");
                                    overlay.FadeOut(); Cursor.Current = Cursors.Default;
                                }
                                else
                                {
                                    //MessageBox.Show(msg);
                                    PageCommon.Alert("打印失败！");
                                    overlay.FadeOut(); Cursor.Current = Cursors.Default;
                                }
                            }
                            else
                            {
                                //MessageBox.Show(msg);

                                PageCommon.Alert("打印失败！");
                                overlay.FadeOut(); Cursor.Current = Cursors.Default;
                            }
                        }
                        else
                        {
                            PageCommon.Error(result.Error.Message); overlay.FadeOut(); Cursor.Current = Cursors.Default;
                        }
                    },
                    this
                );
        }

        private void dtBookDate_ValueChanged(object sender, EventArgs e)
        {
            if (!isDateSelect)
                return;
            GenerDeadLine();
        }

        //计算租赁期限
        private void GenerDeadLine()
        {
            DateTime dtBegin = new DateTime(dtBookDate.Value.Year, dtBookDate.Value.Month, dtBookDate.Value.Day, dtBookDate.Value.Hour, dtBookDate.Value.Minute, 0);
            DateTime dtEnd = new DateTime(dtEndDate.Value.Year, dtEndDate.Value.Month, dtEndDate.Value.Day, dtEndDate.Value.Hour, dtEndDate.Value.Minute, 0);
            if (dtEnd.Subtract(dtBegin).TotalSeconds < 0)
            {
                PageCommon.Alert("预定日期不能大于截止日期，请重新选择");
                return;
            }
            //短租带驾
            //  intHours = Convert.ToInt32(Math.Round(dtEnd.Subtract(dtBegin).TotalHours, 0))/24;
            //intHours = (dtEnd - dtBegin).Days;
            ////txtDeadLine.Text = Math.Round(dtEnd.Subtract(dtBegin).TotalDays, 1).ToString() + " 天";
            //lblDeadLine.Text = intHours.ToString() + "天";
            //this.txtRent.Text = (intHours * Convert.ToDecimal(txtZPrice.Text)).ToString();

        }

        //private void dgvInfo_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        //{
        //    e.CellStyle.WrapMode = DataGridViewTriState.True;
        //    if (this.dgvInfo.Columns[e.ColumnIndex].Name == "客户类型")
        //    {
        //        if (e.Value != null)
        //        {
        //            if (e.Value.ToString().Trim() == "1")
        //            {
        //                e.Value = "个体户客户";
        //            }
        //            else
        //            {
        //                e.Value = "企业客户";
        //            }
        //        }
        //    }
        //}

        private void cmb001_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmb001.Text.Trim() == "接送计时")
            {
                cmb002.Items.Clear();
                cmb002.Items.Add("机场接送单程");
                cmb002.Items.Add("机场接送来回");
                cmb002.Items.Add("包车三小时租金");
                cmb002.Items.Add("包车八小时租金");

            }
            else if (cmb001.Text.Trim() == "长途旅程")
            {
                cmb002.Items.Clear();
                cmb002.Items.Add("长途旅程一");
                cmb002.Items.Add("长途旅程二");
                cmb002.Items.Add("长途旅程三");
            }

            cmb002.SelectedIndex = 0;

        }

        private void cmb002_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (cmb002.Text.Trim())
            {
                case "机场接送单程":
                    lblOutdatedFee.Visible = false;
                    txtOutdatedFee.Visible = false;
                    lblYuan.Visible = false;
                    //txtRent.Text = AirportShuttleOneWay;
                    txtZPrice.Text = AirportShuttleOneWay;
                    if (reserveID == 0)
                    {
                        txtZPrice2.Text = AirportShuttleOneWay;
                    }
                    break;
                case "机场接送来回":
                    lblOutdatedFee.Visible = false;
                    txtOutdatedFee.Visible = false;
                    lblYuan.Visible = false;
                    //txtRent.Text = AirportShuttleTwoWay;
                    txtZPrice.Text = AirportShuttleTwoWay;
                    if (reserveID == 0)
                    {
                        txtZPrice2.Text = AirportShuttleTwoWay;
                    }
                    break;
                case "包车三小时租金":
                    lblOutdatedFee.Visible = true;
                    txtOutdatedFee.Visible = true;
                    lblYuan.Visible = true;
                    //txtRent.Text = Chartered3Rent;
                    txtZPrice.Text = Chartered3Rent;
                    if (reserveID == 0)
                    {
                        txtZPrice2.Text = Chartered3Rent;
                    }
                    txtOutdatedFee.Text = OutdatedFee3;
                    break;
                case "包车八小时租金":
                    lblOutdatedFee.Visible = true;
                    txtOutdatedFee.Visible = true;
                    lblYuan.Visible = true;
                    //txtRent.Text = Chartered8Rent;
                    txtZPrice.Text = Chartered8Rent;
                    if (reserveID == 0)
                    {
                        txtZPrice2.Text = Chartered8Rent;
                    }
                    txtOutdatedFee.Text = OutdatedFee8;
                    break;
                case "长途旅程一":
                    lblOutdatedFee.Visible = false;
                    txtOutdatedFee.Visible = false;
                    lblYuan.Visible = false;
                    //txtRent.Text = LongJourneys1;
                    txtZPrice.Text = LongJourneys1;
                    if (reserveID == 0)
                    {
                        txtZPrice2.Text = LongJourneys1;
                    }
                    break;
                case "长途旅程二":
                    lblOutdatedFee.Visible = false;
                    txtOutdatedFee.Visible = false;
                    lblYuan.Visible = false;
                    //txtRent.Text = LongJourneys2;
                    txtZPrice.Text = LongJourneys2;
                    if (reserveID == 0)
                    {
                        txtZPrice2.Text = LongJourneys2;
                    }
                    break;
                case "长途旅程三":
                    lblOutdatedFee.Visible = false;
                    txtOutdatedFee.Visible = false;
                    lblYuan.Visible = false;
                    //txtRent.Text = LongJourneys3;
                    txtZPrice.Text = LongJourneys3;
                    if (reserveID == 0)
                    {
                        txtZPrice2.Text = LongJourneys3;
                    }
                    break;
            }
        }


        private void dgvUseDate_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            e.CellStyle.WrapMode = DataGridViewTriState.True;


            if (this.dgvUseDate.Columns[e.ColumnIndex].Name == "可用开始时间")
            {
                if (e.Value != null)
                {
                    if (!string.IsNullOrEmpty(e.Value.ToString()))
                        e.Value = Convert.ToDateTime(e.Value.ToString()).ToString("yyyy-MM-dd HH:mm:ss");
                }
            }

            if (this.dgvUseDate.Columns[e.ColumnIndex].Name == "可用结束时间")
            {
                if (e.Value != null && string.IsNullOrEmpty(e.Value.ToString()))
                {
                    if (!string.IsNullOrEmpty(e.Value.ToString()))
                        e.Value = Convert.ToDateTime(e.Value.ToString()).ToString("yyyy-MM-dd HH:mm:ss");
                }
            }
        }

        private void dgvUseDate_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            if (this.dgvUseDate.Rows.Count != 0)
            {
                for (int i = 0; i < this.dgvUseDate.Rows.Count; )
                {
                    this.dgvUseDate.Rows[i].DefaultCellStyle.BackColor = System.Drawing.Color.PapayaWhip;
                    i += 2;
                }
            }
        }

        bool isDateSelect = false;
        private void dgvUseDate_KeyDown(object sender, KeyEventArgs e)
        {
            DateTime dtBegin = DateTime.Now;
            DateTime dtEnd = new DateTime(3000, 1, 1);

            if (e.KeyCode == Keys.Return)
            {
                if (this.dgvUseDate.CurrentRow.Cells["可用开始时间"].Value == null || this.dgvUseDate.CurrentRow.Cells["可用开始时间"].Value.ToString().Trim() == "")
                {
                    dtBegin = new DateTime(1900, 1, 1);
                }
                else
                {
                    dtBegin = Convert.ToDateTime(this.dgvUseDate.CurrentRow.Cells["可用开始时间"].Value.ToString());
                }

                if (this.dgvUseDate.CurrentRow.Cells["可用结束时间"].Value != null && !string.IsNullOrEmpty(this.dgvUseDate.CurrentRow.Cells["可用结束时间"].Value.ToString()))
                {
                    dtEnd = Convert.ToDateTime(this.dgvUseDate.CurrentRow.Cells["可用结束时间"].Value.ToString());

                    dtEndDate.Value = dtEnd;
                    dtBookDate.Value = dtEnd;
                }
                else
                {
                    dtEndDate.Value = dtBegin;
                    dtBookDate.Value = dtBegin;
                }

                dtEndDate.MaxDate = dtEnd;
                dtBookDate.MaxDate = dtEnd;

                dtEndDate.MinDate = dtBegin;
                dtBookDate.MinDate = dtBegin;

                //dtEndDate.Value = dtEnd;
                //dtBookDate.Value = dtEnd;

                //dtBegin = DateTime.Now;
                //dtEnd = new DateTime(3000, 1, 1);

                isDateSelect = true;
                this.dgvUseDate.Visible = false;
                lblDateTitle.Visible = false;
            }
        }

        private void lkbSelectOtherDate_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            dtEndDate.MaxDate = new DateTime(3000, 1, 1);
            dtBookDate.MaxDate = new DateTime(3000, 1, 1);

            dtEndDate.MinDate = new DateTime(1900, 1, 1);
            dtBookDate.MinDate = new DateTime(1900, 1, 1);

            this.dgvUseDate.Visible = true;
            lblDateTitle.Visible = true;
            isDateSelect = false;

        }

        private void BindDateInfo()
        {
            ServiceManipulator.SafeAsyncExecution<ReserveSvc.ReserveServiceSoapClient>(
                   proxy => proxy.GetFreeDateByCarID(sopaHeaderReserveSvc, carId),
                   result =>
                   {
                       if (result.Error == null)
                       {
                           DataSet ds = (DataSet)result.Result;
                           dgvUseDate.AutoGenerateColumns = false;
                           if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                               this.dgvUseDate.DataSource = ds.Tables[0];
                           else
                           {
                               this.dgvUseDate.Visible = false;
                               dtBookDate.MinDate = DateTime.Now;
                               dtEndDate.MinDate = DateTime.Now;

                               isDateSelect = true;
                               lblDateTitle.Visible = false;
                               lkbSelectOtherDate.Enabled = false;
                           }
                       }
                       else
                       {
                           PageCommon.Error(result.Error.Message); overlay.FadeOut(); Cursor.Current = Cursors.Default;
                       }
                   },
                   this
               );
        }

        private void btnAddCustomer_Click(object sender, EventArgs e)
        {
            SystemAdminCustomer form = new SystemAdminCustomer();
            form.ShowDialog();
        }

        private void Cmbpaytype_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbpaytype.Text.Trim() == "会员积分")
            {
                displayPoints();
            }
            else
            {
                unDisplayPoints();
            }
        }

        private void displayPoints()
        {
            lblPoints.Visible = true;
            lblPoints1.Visible = true;
            lblPoints2.Visible = true;
            lblPoints.Text = customerInfo.Points.ToString();
        }

        private void unDisplayPoints()
        {
            lblPoints.Visible = false;
            lblPoints1.Visible = false;
            lblPoints2.Visible = false;
            lblPoints.Text = "0";
        }

    }
}
